package sbcc.edu.blackjack;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.wb.swt.SWTResourceManager;

import sbcc.edu.blackjack.client.ClientMain;
import sbcc.edu.blackjack.client.ClientTable;

public class MainWindow {

	protected Shell shell;
	Properties appSettings = new Properties();
	Cursor defaultCursor; // To change the cursor to an arrow at any point after MainWindow() has executed, use
							// shell.setCursor(defaultCursor);
	Cursor waitCursor; // To change the cursor to an hourglass at any point after MainWindow() has executed, use
						// shell.setCursor(waitCursor);
	private Composite clientArea;
	private Label statusText;
	private Display display;
	private static Text bettingBox;
	private static Button hitButton;
	private static Button stayButton;
	private static Button submitBetButton;
	private static Button doubleDownButton;
	private ClientOperator operator;
	

	/**
	 * Launch the application.
	 * 
	 * @param args
	 */
	public MainWindow(ClientOperator operator) {
       this.operator = operator;
       try {
    	   this.open();
       } catch (Exception e) {
			e.printStackTrace();
		}
       
	}



	/**
	 * Open the window.
	 */
	public void open() {
		 display = Display.getDefault();
		createContents();

		setPreferences();
		waitCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT);
		defaultCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_ARROW);
		clientArea.setFocus();

		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	public void update(ClientTable t){
		//show some icons based on the client table
	}

	/**
	 * Open the window.
	 */
	public void openForUnitTesting() {
		createContents();

		setPreferences();
		waitCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT);
		defaultCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_ARROW);
		clientArea.setFocus();

		shell.open();
		shell.layout();
	}


	public void closeForUnitTesting() {
		shell.dispose();
	}


	// Load application settings from .ini file
	private void setPreferences() {
		try {
			appSettings.load(new FileInputStream("appsettings.ini"));
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}

		// By default, center window
		int width = Integer.parseInt(appSettings.getProperty("width", "640"));
		int height = Integer.parseInt(appSettings.getProperty("height", "480"));
		Rectangle screenBounds = shell.getDisplay().getBounds();
		int defaultTop = (screenBounds.height - height) / 2;
		int defaultLeft = (screenBounds.width - width) / 2;
		int top = Integer.parseInt(appSettings.getProperty("top", String.valueOf(defaultTop)));
		int left = Integer.parseInt(appSettings.getProperty("left", String.valueOf(defaultLeft)));
		shell.setSize(width, height);
		shell.setLocation(left, top);
		saveShellBounds();
	}


	// Save window location in appSettings hash table
	private void saveShellBounds() {
		// Save window bounds in app settings
		Rectangle bounds = shell.getBounds();
		appSettings.setProperty("top", String.valueOf(bounds.y));
		appSettings.setProperty("left", String.valueOf(bounds.x));
		appSettings.setProperty("width", String.valueOf(bounds.width));
		appSettings.setProperty("height", String.valueOf(bounds.height));
	}


	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell(display, SWT.CLOSE | SWT.TITLE | SWT.MIN );
		shell.setMinimumSize(new Point(800, 565));
		shell.addControlListener(new ShellControlListener());
		shell.addDisposeListener(new ShellDisposeListener());
		shell.setImage(SWTResourceManager.getImage(MainWindow.class, "/images/16x16.png"));
		shell.setSize(640, 480);
		shell.setText("BARJ - BlackJack");
		shell.setLayout(null);
		
		Menu menu = new Menu(shell, SWT.BAR);
		shell.setMenuBar(menu);

		MenuItem fileMenuItem = new MenuItem(menu, SWT.CASCADE);
		fileMenuItem.setText("&File");

		Menu menu_1 = new Menu(fileMenuItem);
		fileMenuItem.setMenu(menu_1);

		MenuItem newFileMenuItem = new MenuItem(menu_1, SWT.NONE);
		newFileMenuItem.setImage(SWTResourceManager.getImage(MainWindow.class, "/images/new.gif"));
		newFileMenuItem.setText("&New");

		MenuItem openFileMenuItem = new MenuItem(menu_1, SWT.NONE);
		openFileMenuItem.addSelectionListener(new OpenFileMenuItemSelectionListener());
		openFileMenuItem.setImage(SWTResourceManager.getImage(MainWindow.class, "/images/open.gif"));
		openFileMenuItem.setText("&Open");

		MenuItem closeFileMenuItem = new MenuItem(menu_1, SWT.NONE);
		closeFileMenuItem.setText("&Close");

		new MenuItem(menu_1, SWT.SEPARATOR);

		MenuItem saveFileMenuItem = new MenuItem(menu_1, SWT.NONE);
		saveFileMenuItem.setImage(SWTResourceManager.getImage(MainWindow.class, "/images/save.gif"));
		saveFileMenuItem.setText("&Save");

		new MenuItem(menu_1, SWT.SEPARATOR);

		MenuItem exitMenuItem = new MenuItem(menu_1, SWT.NONE);
		exitMenuItem.addSelectionListener(new ExitMenuItemSelectionListener());
		exitMenuItem.setText("E&xit");

		MenuItem helpMenuItem = new MenuItem(menu, SWT.CASCADE);
		helpMenuItem.setText("&Help");

		Menu menu_2 = new Menu(helpMenuItem);
		helpMenuItem.setMenu(menu_2);

		MenuItem aboutMenuItem = new MenuItem(menu_2, SWT.NONE);
		aboutMenuItem.addSelectionListener(new AboutMenuItemSelectionListener());
		aboutMenuItem.setText("&About");

		ToolBar toolBar = new ToolBar(shell, SWT.FLAT | SWT.RIGHT);
		toolBar.setBounds(3, 3, 778, 16);

		

		

		clientArea = new Composite(shell, SWT.NONE);
		clientArea.setBounds(3, 31, 778, 444);
		
		 hitButton = new Button(clientArea, SWT.NONE);
		//TODO set visibility to false initially until players Turn
		hitButton.setVisible(false);
		hitButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				//Player Clicked on Hit
				
			}
		});
		hitButton.setBounds(90, 409, 75, 25);
		hitButton.setText("Hit");
		
		 stayButton = new Button(clientArea, SWT.NONE);
		//TODO set visibility to false initially until players Turn
		stayButton.setVisible(false);
		stayButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				//player selected Stay Button 
				
			}
		});
		stayButton.setBounds(603, 409, 75, 25);
		stayButton.setText("Stay");
		
		 doubleDownButton = new Button(clientArea, SWT.NONE);
		//TODO set visibility to false initially until players Turn and they have two of the same cards
		doubleDownButton.setVisible(false);
		doubleDownButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				//Player selected double Down option
			}
		});
		doubleDownButton.setBounds(684, 409, 84, 25);
		doubleDownButton.setText("Double Down");
		
		bettingBox = new Text(clientArea, SWT.BORDER);
		bettingBox.setBounds(348, 225, 120, 21);
		bettingBox.setVisible(true);
		 submitBetButton = new Button(clientArea, SWT.NONE);
		 submitBetButton.addSelectionListener(new SelectionAdapter() {
		 	@Override
		 	public void widgetSelected(SelectionEvent e) {
		 		
		 	}
		 });
		submitBetButton.setBounds(371, 257, 75, 25);
		submitBetButton.setText("Make Bet");
		submitBetButton.setVisible(true);
		Image image = new Image(
			    display, MainWindow.class.getResourceAsStream(
			      "blackJack-Table.png"));
		shell.setBackgroundImage(image);
	       shell.setBackgroundMode(SWT.INHERIT_FORCE);  
	       shell.setFullScreen(true);

	

		Composite statusArea = new Composite(shell, SWT.NONE);
		statusArea.setBounds(0, 500, 800, 19);
		statusArea.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		FillLayout fl_statusArea = new FillLayout(SWT.HORIZONTAL);
		fl_statusArea.marginWidth = 2;
		fl_statusArea.marginHeight = 2;
		statusArea.setLayout(fl_statusArea);

		statusText = new Label(statusArea, SWT.NONE);
		statusText.setText("Ready");

	}


	private void handleFileOpenRequest() {
		FileDialog dialog = new FileDialog(shell, SWT.OPEN);
		String filename = dialog.open();
		if (filename != null) {
			shell.setText(filename);
		}
	}


	private class ExitMenuItemSelectionListener extends SelectionAdapter {

		

		@Override
		public void widgetSelected(SelectionEvent e) {
			try {
				// Save app settings to file
				appSettings.store(new FileOutputStream("appsettings.ini"), "");
			} catch (Exception ex) {
			}
			ClientMain.quit();
			shell.dispose();
		}
	}


	private class OpenFileMenuItemSelectionListener extends SelectionAdapter {

		@Override
		public void widgetSelected(SelectionEvent e) {
			handleFileOpenRequest();
		}
	}


	private class OpenToolItemSelectionListener extends SelectionAdapter {

		@Override
		public void widgetSelected(SelectionEvent e) {
			handleFileOpenRequest();
		}
	}


	private class AboutMenuItemSelectionListener extends SelectionAdapter {

		@Override
		public void widgetSelected(SelectionEvent e) {
			MessageBox message = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
			message.setText("About Change_This_Title");
			message.setMessage("BARJ Blackjack\n\nWritten by Jason Howell, Aaron Lamar, & Ray Kolbe\n\n version 0.1");
			message.open();
		}
	}


	private class ShellDisposeListener implements DisposeListener {

		public void widgetDisposed(DisposeEvent arg0) {
			try {
				// Save app settings to file
				appSettings.store(new FileOutputStream("appsettings.ini"), "");
			} catch (Exception ex) {
			}
		}
	}


	private class ShellControlListener extends ControlAdapter {

		@Override
		public void controlMoved(ControlEvent e) {
			try {
				saveShellBounds();
			} catch (Exception ex) {
				setStatus(ex.getMessage());
			}
		}


		@Override
		public void controlResized(ControlEvent e) {
			try {
				saveShellBounds();
			} catch (Exception ex) {
				setStatus(ex.getMessage());
			}
		}
	}


	private void setStatus(String message) {
		statusText.setText(message);
	}
	public static  void setBettingVisible() {
		bettingBox.setVisible(true);
		submitBetButton.setVisible(true);
	}
	public  void setBettingNotVisible() {
		bettingBox.setVisible(false);
		submitBetButton.setVisible(false);
	}
	public static void setGameButtonsVisible(boolean DoubleDown) {
		hitButton.setVisible(true);
		stayButton.setVisible(true);
		if(DoubleDown)
		doubleDownButton.setVisible(true);
	}
	public void setGameButtonsNotVisible() {
		hitButton.setVisible(false);
		stayButton.setVisible(false);
		doubleDownButton.setVisible(false);
	}
}
